<template>
  <div class="user">
    <div class="avatar">
      <el-avatar v-if="userId" size="small" :src="avatarUrl"/>
    </div>
    <div>{{ username || "未知用户" }}</div>
  </div>
</template>

<script>
import {getUserBasicInformation} from "@/api/system/user";

export default {
  name: "UserAndAvatar",
  data() {
    return {
      url: "",
      username: "",
    };
  },
  props: {
    userId: [Number, String],
  },
  computed: {
    avatarUrl() {
      return this.url || require("@/assets/images/profile.jpg");
    },
  },
  watch: {
    userId: {
      handler(newVal) {
        if (newVal) this.getUserInfo();
      },
      immediate: true,
    },
  },
  methods: {
    async getUserInfo() {
      if (!this.userId) return;
      let userAvatar = this.$store.state.userAvatar.userAvatars
      if (userAvatar.get(this.userId)) {
        this.url = userAvatar.get(this.userId).avatar
        this.username = userAvatar.get(this.userId).userName
      } else {
        const {data} = await getUserBasicInformation(this.userId);
        console.log('查询');
        await this.$store.dispatch("userAvatar/setUserAvatars", data)
        this.url = data.avatar || "";
        this.username = data.userName || "未知用户";
      }
    },
  },
};
</script>

<style scoped>
.user {
  display: flex;
  align-items: center;
  gap: 10px; /* 控制头像和用户名的间距 */
  width: 100px;
}

.avatar {
  width: 28px;
  height: 28px;
}
</style>
